﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Windows.Media.Imaging;
using System.IO;
using BrokerBase.Lib.Person;
using System.Windows.Media;

namespace Broker.View.Converter
{
    public class PersonPhotoConverter : IValueConverter
    {

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            IPerson person = value as IPerson;

            ImageSource img = null;

            try
            {
                if (person != null)
                {
                    if (person.Photo != null && person.Photo.Count() > 0)
                    {
                        BitmapImage bitImage = null;
                        MemoryStream ms = new MemoryStream(person.Photo);
                        bitImage = new BitmapImage();
                        bitImage.BeginInit();
                        bitImage.StreamSource = ms;
                        bitImage.EndInit();

                        img = bitImage;
                    }
                    else
                    {
                        string packUri = null;

                        if (person.Sex == SexType.Male)
                            packUri = "pack://application:,,,/Broker.View;Component/images/user_male.png";
                        else
                            packUri = "pack://application:,,,/Broker.View;Component/images/user_female.png";

                        img = new ImageSourceConverter().ConvertFromString(packUri) as ImageSource;
                    }
                }
                return img;
            }
            catch (Exception ex)
            {
                string packUri = null;

                if (person.Sex == SexType.Male)
                    packUri = "pack://application:,,,/Broker.View;Component/images/user_male.png";
                else
                    packUri = "pack://application:,,,/Broker.View;Component/images/user_female.png";

                img = new ImageSourceConverter().ConvertFromString(packUri) as ImageSource;

                throw ex;
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
